import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class Test {

    public int[] smallestK(int[] array,int k) {   //寻找前k个大的元素
        int[] ret = new int[k];
        if (array == null || k == 0) {
            return ret;
        }
        Queue<Integer> minHeap = new PriorityQueue<>(array.length);
        for (int x : array) {
            minHeap.offer(x);
        }
        for (int i = 0; i < k; i++) {
            ret[i] = minHeap.poll();
        }
        return ret;
    }

    public static int[] maxK(int[] array, int k) {  //topK问题利用大小根堆来解决
        int[] ret = new int[k];
        if (array == null) {
            return ret;
        }
        Queue<Integer> priorityQueue = new PriorityQueue<>(k);
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }
        for (int i = k; i < array.length; i++) {
            if (array[i] > priorityQueue.peek()) {
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] array = {1,5,43,3,2,7,98,41,567,78};
        int[] ret = maxK(array,3);
        System.out.println(Arrays.toString(ret));
    }

}
